/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin			*/
/*	Project:	GlbCloud			*/
/*	Author:		gong_libin			*/
/*	Date:		2012_01_12			*/
/*	File:		MrShm.cpp			*/
/********************************************************/

#include "MrShm.h"

CMrShm::CMrShm()
{
	m_pShm = NULL;
	m_iShm = MR_FAILURE;
}

CMrShm::~CMrShm()
{
}

int CMrShm::MrShmGetID()
{
	return m_iShm;
}

void* CMrShm::MrShmGetShm()
{
	return m_pShm;
}

void CMrShm::MrShmPutID(int iID)
{
	m_iShm = iID;

	return;
}

void CMrShm::MrShmReset(ULONG ulSize)
{
	if (NULL != m_pShm) {
		memset(m_pShm, '\0', ulSize);
	}

	return;
}

void CMrShm::MrShmDetach()
{
	if (NULL != m_pShm) {
		shmdt(m_pShm);
	}

	return;
}

void* CMrShm::MrShmAttach()
{
	void* pReturn = NULL;

	if (MR_FAILURE != m_iShm) {
		pReturn = m_pShm = shmat(m_iShm, NULL, 0);
		if ((void*)MR_FAILURE == pReturn) {
			MR_ERROR("%s\n", strerror(errno));
		}
	}

	return pReturn;
}

void CMrShm::MrIpcSetKernel(ULONG ulMax, ULONG ulAll)
{
	char szCmd[MR_PACKET] = { 0 };

	sprintf(szCmd, "sysctl -w kernel.shmmax=%ld", ulMax);
	system(szCmd);

	memset(szCmd, '\0', MR_PACKET);
	sprintf(szCmd, "sysctl -w kernel.shmall=%ld", ulAll);
	system(szCmd);

	return;
}

int CMrShm::MrIpcCreate(key_t iKey, ULONG ulSize)
{
	int iReturn = MR_SUCCESS;

	m_iShm = shmget(iKey, ulSize, IPC_CREAT | 0777);
	if (MR_FAILURE == m_iShm) {
		MR_ERROR("%s\n", strerror(errno));
		iReturn = MR_FAILURE;
	}

	if (NULL == MrShmAttach()) {
		iReturn = MR_FAILURE;
	}

	return iReturn;
}

void CMrShm::MrIpcDelete()
{
	if (MR_FAILURE != m_iShm) {
		shmctl(m_iShm, IPC_RMID, 0);
	}

	return;
}
